package com.leyuan.printer.mvp.presenter;

import android.content.Context;
import android.widget.Toast;

import com.google.gson.Gson;
import com.leyuan.printer.R;
import com.leyuan.printer.config.Constant;
import com.leyuan.printer.entry.PrintResult;
import com.leyuan.printer.entry.PrintResult2;
import com.leyuan.printer.http.RetrofitHelper;
import com.leyuan.printer.http.api.PrintService;
import com.leyuan.printer.http.subscriber.BaseSubscriber;
import com.leyuan.printer.mvp.model.PrinterModel;
import com.leyuan.printer.mvp.view.BannerViewListener;
import com.leyuan.printer.mvp.view.PrintInfoListener;
import com.leyuan.printer.ui.App;
import com.leyuan.printer.utils.ToastGlobal;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;

import okhttp3.ResponseBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by user on 2017/4/17.
 */


public class PrinterPresenter {

    private Context context;
    private PrinterModel model;
    private PrintInfoListener printInfoListenerlistener;
    private BannerViewListener bannerViewListener;

    public PrinterPresenter() {

    }


    public PrinterPresenter(Context context) {
        this.context = context;
        model = new PrinterModel();
    }

    public void setPrintInfoListener(PrintInfoListener printInfoListenerlistener) {
        this.printInfoListenerlistener = printInfoListenerlistener;
    }

    public void setBannerViewListener(BannerViewListener bannerViewListener) {
        this.bannerViewListener = bannerViewListener;
    }

    public void getPrintInfo(final String appointCode) {
      /*  model.getPrintInfo(code, new BaseSubscriber<PrintResult>(context) {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
//                ToastGlobal.showShort(e.getMessage());
                if (printInfoListenerlistener != null)
                    printInfoListenerlistener.onGetPrintInfo(null,code);
            }

            @Override
            public void onNext(PrintResult printResult) {
                if (printInfoListenerlistener != null)
                    printInfoListenerlistener.onGetPrintInfo(printResult,code);
            }
        });*/


        // RetrofitHelper.createApi(PrintService.class).getPrintInfo2(appointCode, App.getInstance().getDevicesId())

        RetrofitHelper.createApi(PrintService.class).getPrintInfo2(appointCode, App.getInstance().getChannel())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ResponseBody>() {
                               @Override
                               public void onCompleted() {

                               }

                               @Override
                               public void onError(Throwable e) {
                                   if (e instanceof SocketTimeoutException) {
                                       ToastGlobal.showShortConsecutive(R.string.connect_timeout);
                                   } else if (e instanceof ConnectException) {
                                       ToastGlobal.showShortConsecutive(R.string.connect_break);
                                   } else {
                                       ToastGlobal.showLongCenter("" + e.getMessage());
                                   }
                                   if (printInfoListenerlistener != null)
                                       printInfoListenerlistener.onGetPrintInfo(false, null, appointCode);
                               }

                               @Override
                               public void onNext(ResponseBody responseBody) {


                                   try {


                                       String jsonValue = responseBody.string();


//                                       String  jsonValue = "jsonValue = \"{\"code\":1,\"msg\":\"\",\"data\":[{\"print\":0,\"title\":\"爱动健身\",\"item\":[{\"name\":\"商品名称\",\"value\":\"凉凉(x1)\"},{\"name\":\"提货门店\",\"value\":\"威尔仕南丰城\"},{\"name\":\"提货时间\",\"value\":\"2018-08-24 \"},{\"name\":\"打印时间\",\"value\":\"2018-08-24 15:56:20\"},{\"name\":\"核 销 码\",\"value\":\"1011808243900062340\"},{\"name\":\"订单金额\",\"value\":\"0.00\"},{\"name\":\"实付金额\",\"value\":\"0.01\"},{\"name\":\"会员姓名\",\"value\":\"三月末\"},{\"name\":\"会员手机\",\"value\":\"18556502713\"}]}]}\"\n" +
//                                           "jsonValue = \"{\"code\":1,\"msg\":\"\",\"data\":[{\"print\":0,\"title\":\"爱动健身\",\"item\":[{\"name\":\"商品名称\",\"value\":\"凉凉(x1)\"},{\"name\":\"提货门店\",\"value\":\"威尔仕南丰城\"},{\"name\":\"提货时间\",\"value\":\"2018-08-24 \"},{\"name\":\"打印时间\",\"value\":\"2018-08-24 15:56:20\"},{\"name\":\"核 销 码\",\"value\":\"1011808243900062340\"},{\"name\":\"订单金额\",\"value\":\"0.00\"},{\"name\":\"实付金额\",\"value\":\"0.01\"},{\"name\":\"会员姓名\",\"value\":\"三月末\"},{\"name\":\"会员手机\",\"value\":\"18556502713\"}]}]}\"";
//

                                       if (jsonValue != null) {
                                           Gson gson = new Gson();
                                           JSONObject jsonObject = new JSONObject(jsonValue);


                                           if (jsonObject.getInt("code") == 1) {
                                               Object json = jsonObject.get("data");

                                               if (json instanceof JSONObject) {
                                                   PrintResult printResult = gson.fromJson(jsonValue, PrintResult.class);
                                                   System.out.print("JSONOBJECT");

                                                   if (printInfoListenerlistener != null)
                                                       printInfoListenerlistener.onGetPrintInfoOld(printResult, appointCode);
                                                   // Toast.makeText(context, "获取的data对象是JSONObject" + "值是" + jsonValue, Toast.LENGTH_SHORT).show();

                                               } else if (json instanceof JSONArray) {
                                                   PrintResult2 printResult = gson.fromJson(jsonValue, PrintResult2.class);

                                                   System.out.print("JSONArray");

                                                   if (printInfoListenerlistener != null && printResult.data != null) {
                                                       printInfoListenerlistener.onGetPrintInfo(true, printResult, appointCode);


                                                       //  Toast.makeText(context, "获取的data对象是JSONArray" + "值是" + jsonValue, Toast.LENGTH_SHORT).show();

                                                   } else {
                                                       Toast.makeText(context, printResult.msg, Toast.LENGTH_SHORT).show();
                                                       printInfoListenerlistener.onGetPrintInfo(false, null, appointCode);
                                                   }

                                               }

                                           } else {
                                               printInfoListenerlistener.onGetPrintInfo(false, null, appointCode);
                                               Toast.makeText(context, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                                           }


                                       } else {
                                           printInfoListenerlistener.onGetPrintInfo(false, null, appointCode);
                                       }
                                   } catch (Exception e) {
                                       e.printStackTrace();
                                   }
                               }
                           }
                );


        /***********************************************************/


//        RetrofitHelper.createApi(PrintService.class).getPrintInfo(appointCode, App.getInstance().getDevicesId())
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Subscriber<PrintResult2>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        if (e instanceof SocketTimeoutException) {
//                            ToastGlobal.showShortConsecutive(R.string.connect_timeout);
//                        } else if (e instanceof ConnectException) {
//                            ToastGlobal.showShortConsecutive(R.string.connect_break);
//                        } else {
//                            ToastGlobal.showLongCenter("" + e.getMessage());
//                        }
//                        if (printInfoListenerlistener != null)
//                            printInfoListenerlistener.onGetPrintInfo(false, null, appointCode);
//
//
//                    }
//
//                    @Override
//                    public void onNext(PrintResult2 printResult) {
//                        if (printInfoListenerlistener != null && printResult.data != null) {
//                            printInfoListenerlistener.onGetPrintInfo(true, printResult, appointCode);
//
//                        } else {
//                            Toast.makeText(context, printResult.msg, Toast.LENGTH_SHORT).show();
//                            printInfoListenerlistener.onGetPrintInfo(false, null, appointCode);
//                        }
//                    }
//                });


    }


    public void getPrintInfo22(final String appointCode, String value) {
      /*  model.getPrintInfo(code, new BaseSubscriber<PrintResult>(context) {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
//                ToastGlobal.showShort(e.getMessage());
                if (printInfoListenerlistener != null)
                    printInfoListenerlistener.onGetPrintInfo(null,code);
            }

            @Override
            public void onNext(PrintResult printResult) {
                if (printInfoListenerlistener != null)
                    printInfoListenerlistener.onGetPrintInfo(printResult,code);
            }
        });*/


        // RetrofitHelper.createApi(PrintService.class).getPrintInfo2(appointCode, App.getInstance().getDevicesId())

        RetrofitHelper.createApi(PrintService.class).getPrintInfo2(appointCode, value)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ResponseBody>() {
                               @Override
                               public void onCompleted() {

                               }

                               @Override
                               public void onError(Throwable e) {
                                   if (e instanceof SocketTimeoutException) {
                                       ToastGlobal.showShortConsecutive(R.string.connect_timeout);
                                   } else if (e instanceof ConnectException) {
                                       ToastGlobal.showShortConsecutive(R.string.connect_break);
                                   } else {
                                       ToastGlobal.showLongCenter("" + e.getMessage());
                                   }
                                   if (printInfoListenerlistener != null)
                                       printInfoListenerlistener.onGetPrintInfo(false, null, appointCode);
                               }

                               @Override
                               public void onNext(ResponseBody responseBody) {


                                   try {


                                       String jsonValue = responseBody.string();


//                                       String  jsonValue = "jsonValue = \"{\"code\":1,\"msg\":\"\",\"data\":[{\"print\":0,\"title\":\"爱动健身\",\"item\":[{\"name\":\"商品名称\",\"value\":\"凉凉(x1)\"},{\"name\":\"提货门店\",\"value\":\"威尔仕南丰城\"},{\"name\":\"提货时间\",\"value\":\"2018-08-24 \"},{\"name\":\"打印时间\",\"value\":\"2018-08-24 15:56:20\"},{\"name\":\"核 销 码\",\"value\":\"1011808243900062340\"},{\"name\":\"订单金额\",\"value\":\"0.00\"},{\"name\":\"实付金额\",\"value\":\"0.01\"},{\"name\":\"会员姓名\",\"value\":\"三月末\"},{\"name\":\"会员手机\",\"value\":\"18556502713\"}]}]}\"\n" +
//                                           "jsonValue = \"{\"code\":1,\"msg\":\"\",\"data\":[{\"print\":0,\"title\":\"爱动健身\",\"item\":[{\"name\":\"商品名称\",\"value\":\"凉凉(x1)\"},{\"name\":\"提货门店\",\"value\":\"威尔仕南丰城\"},{\"name\":\"提货时间\",\"value\":\"2018-08-24 \"},{\"name\":\"打印时间\",\"value\":\"2018-08-24 15:56:20\"},{\"name\":\"核 销 码\",\"value\":\"1011808243900062340\"},{\"name\":\"订单金额\",\"value\":\"0.00\"},{\"name\":\"实付金额\",\"value\":\"0.01\"},{\"name\":\"会员姓名\",\"value\":\"三月末\"},{\"name\":\"会员手机\",\"value\":\"18556502713\"}]}]}\"";
//

                                       if (jsonValue != null) {
                                           Gson gson = new Gson();
                                           JSONObject jsonObject = new JSONObject(jsonValue);


                                           if (jsonObject.getInt("code") == 1) {
                                               Object json = jsonObject.get("data");

                                               if (json instanceof JSONObject) {
                                                   PrintResult printResult = gson.fromJson(jsonValue, PrintResult.class);

                                                   System.out.print("JSONOBJECT");

                                                   if (printInfoListenerlistener != null) {
                                                       printInfoListenerlistener.onGetPrintInfoOld(printResult, appointCode);
                                                   }


                                               } else if (json instanceof JSONArray) {
                                                   PrintResult2 printResult = gson.fromJson(jsonValue, PrintResult2.class);

                                                   System.out.print("JSONArray");

                                                   if (printInfoListenerlistener != null && printResult.data != null) {
                                                       printInfoListenerlistener.onGetPrintInfo(true, printResult, appointCode);


                                                       //  Toast.makeText(context, "获取的data对象是JSONArray" + "值是" + jsonValue, Toast.LENGTH_SHORT).show();

                                                   } else {
                                                       Toast.makeText(context, printResult.msg, Toast.LENGTH_SHORT).show();
                                                       printInfoListenerlistener.onGetPrintInfo(false, null, appointCode);
                                                   }

                                               }

                                           } else {
                                               printInfoListenerlistener.onGetPrintInfo(false, null, appointCode);
                                               Toast.makeText(context, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                                           }


                                       } else {
                                           printInfoListenerlistener.onGetPrintInfo(false, null, appointCode);

                                       }
                                   } catch (Exception e) {
                                       e.printStackTrace();
                                   }
                               }
                           }
                );


        /***********************************************************/


//        RetrofitHelper.createApi(PrintService.class).getPrintInfo(appointCode, App.getInstance().getDevicesId())
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Subscriber<PrintResult2>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        if (e instanceof SocketTimeoutException) {
//                            ToastGlobal.showShortConsecutive(R.string.connect_timeout);
//                        } else if (e instanceof ConnectException) {
//                            ToastGlobal.showShortConsecutive(R.string.connect_break);
//                        } else {
//                            ToastGlobal.showLongCenter("" + e.getMessage());
//                        }
//                        if (printInfoListenerlistener != null)
//                            printInfoListenerlistener.onGetPrintInfo(false, null, appointCode);
//
//
//                    }
//
//                    @Override
//                    public void onNext(PrintResult2 printResult) {
//                        if (printInfoListenerlistener != null && printResult.data != null) {
//                            printInfoListenerlistener.onGetPrintInfo(true, printResult, appointCode);
//
//                        } else {
//                            Toast.makeText(context, printResult.msg, Toast.LENGTH_SHORT).show();
//                            printInfoListenerlistener.onGetPrintInfo(false, null, appointCode);
//                        }
//                    }
//                });


    }


    public void printSuccessNotify(String code,String deviceId) {
        RetrofitHelper.createApi(PrintService.class).printSuccessNotify(code,deviceId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {


                        Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {

                        try {
                            String value = responseBody.string();
                            if (value!=null){
                               // Toast.makeText(context, value, Toast.LENGTH_SHORT).show();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }


                    }
                });
    }

    @Deprecated
    public void printSuccess(String code, String lessonType) {
        model.printSuccess(code, lessonType, new Subscriber<PrintResult>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                if (printInfoListenerlistener != null) {
                    printInfoListenerlistener.onPostPrintState(false);
                }
            }

            @Override
            public void onNext(PrintResult printResult) {
                if (printInfoListenerlistener != null) {
                    printInfoListenerlistener.onPostPrintState(true);
                }
            }
        });
    }

    public void getBanners() {
        model.getBanners(new BaseSubscriber<ArrayList<String>>(context) {
            @Override
            public void onNext(ArrayList<String> strings) {
                if (strings != null)
                    Constant.BANNERS = strings;
                if (bannerViewListener != null) {
                    bannerViewListener.onGetBannerArray(strings);
                }
            }
        });
    }
}
